(function ($) {
    const userMessage = {
        nickName: $('#profile_block a:first').text().trim(),
        blogAge: $('#profile_block a:nth-child(3)').text().trim(),
        followers: $('#profile_block a:nth-child(5)').text().trim(),
        focus: $('#profile_block a:nth-child(7)').text().trim(),
    }
    const icons = {
        news: '#ac-gonggao',                   // 公告
        catListTitle: '#ac-mulu',              // 侧边栏主标题
        readMore: '#ac-xiangyou',              // 首页阅读全文
        catalog: '#ac-mulu2',                  // 随笔页文章目录
        signature: '#ac-3banquanshengming',    // 随笔页版权声明
        writeComment: '#ac-bi',                     // 写评论
        commentList: '#ac-pinglun',            // 评论列表
        weibo: '#ac-weibo',                    // 分享到微博
        wechat: '#ac-wechat',                  //分享到微信
        follow: '#ac-follow',                  //关注
        collect: '#ac-collect',                //收藏
        like: '#ac-like',                      //点赞
        back2top: '#ac-back2top',              //返回顶部
    }
    const urls = {
        css: {
            theme: {
                atomOneDark: 'atomOneDark',
                atomOneLight: 'atomOneLight'
            }
        },
        script: {
            lineNumbers: 'lineNumbers',
            iconfont: '//at.alicdn.com/t/font_1587109_olf5oxd7zbd.js'
        },
        repositories: window.rep
    }
    class Light {
        constructor() {
            this.defaultOptions = window.userOptions;
            this.v = 'v1.0.0';
        }

        // 初始化
        init() {
            console.log('light init');
            if (this.isPostPage) {
                this.hidComments();
                this.setCatalog();
                this.setPostTools();
                this.setCopyBtn();
                this.setCodeTheme();
                this.setLineNumbers();
                this.setPostSignature();
                this.setBack2Top();
            }
            this.showElements();
            this.setIcon();
            this.setFooter();
            this.setFavicon();
            this.hideLoading();
        }

        // 获取emoji
        get emoji() {
            const emoji = ['💌', '💎', '🔪', '💈', '🚪'];
            const random = Math.floor(Math.random() * emoji.length + 1);
            return emoji[random];
        }

        // 判断是否为随笔页
        get isPostPage() {
            return $('#post_detail').length > 0;
        }

        // 获取接口
        get api() {
            return {
                acg: 'https://api.77sec.cn/ACG/',
                bing: 'https://bing.biturl.top/?resolution=1920&format=image&index=0&mkt=zh-CN',
                poems: 'https://api.gushi.ci/all.json', //content author
                motto: 'https://v1.hitokoto.cn/', //hitokoto
                wyyComments: 'https://api.comments.hk/', //comment_content
                zhihu: 'https://news-at.zhihu.com/api/4/news/latest', //top_stories
                todayInHistory: 'https://api.ooopn.com/history/api.php?type=json', //content
                dailyArticle: 'https://interface.meiriyiwen.com/article/today?dev=1', //title author content digest
            }
        }

        // 隐藏loading
        hideLoading() {
            $('#loading').fadeOut();
        }

        /**
        * 加载 js/css文件
        *
        * @param {*} file  本地文件名或CDN
        * @param {*} type  'css' / 'js' / 'cssCDN' / 'jsCDN'
        */
        loaderFile(file, type) {
            const repositoriesUrl = urls.repositories.package + '/assets';
            const cssUrl = repositoriesUrl + '/css/' + file + '.css';
            const jsUrl = repositoriesUrl + '/js/' + file + '.min.js';

            switch (type) {
                case 'css':
                    let cn = `<link rel="stylesheet" href="${cssUrl}">`;
                    $("head").append(cn);
                    break;
                case 'js':
                    if (file === 'lineNumbers') {
                        $.getScript(jsUrl, () => { hljs.initLineNumbersOnLoad(); });
                    } else {
                        $.getScript(jsUrl);
                    }
                    break;
                case 'cssCDN':
                    let cd = `<link rel="stylesheet" href="${file}">`;
                    $("head").append(cd);
                    break;
                case 'jsCDN':
                    $.getScript(file);
                    break;
                default:
                    break;
            }
        }

        // 指定icon插入svg
        iconInSvg(icon) {
            return `<svg class="icon" aria-hidden="true">
                  <use xlink:href="${icon}"></use>
              </svg>`;
        }

        // 如果没有评论，隐藏评论列表
        hidComments() {
            if ($('#blog-comments-placeholder')[0].childElementCount === 0)
                $('#blog-comments-placeholder').hide();
        }

        // 非随笔页显示侧边栏
        showElements() {
            if (!this.isPostPage) {
                $('#sideBar').css({
                    'display': 'block',
                    'animation': 'fadeInLeft .5s ease-in 0s'
                });
            }
        }

        // 返回顶部
        setBack2Top() {
            const svg = this.iconInSvg(icons.back2top);
            let dom = $(`<div id="back2Top">${svg}</div>`)
                .appendTo('body')
                .click(() => {
                    $("html, body").animate({ scrollTop: 0 }, 300);
                });
            $(window).bind("scroll", () => {
                let scrollTop = $(document).scrollTop();
                scrollTop > 0 ? dom.show() : dom.hide();
            });
        }

        // 设置随笔页左侧按钮
        setPostTools() {
            const str = $('#author_profile_detail :last-child').text();
            const followCount = str.substr(str.length - 1, 1);
            const likeCount = $('#digg_count').text();
            $('#mainContent').append($('#blog_post_info'));
            $('#blog_post_info_block>#blog_post_info').remove();
            //设置icon
            return new Promise((resolve, reject) => {
                //点赞
                $('#green_channel_digg').empty()
                    .html(this.iconInSvg(icons.like))
                    .append(`<span id="like-count">${likeCount}</span>`);
                //关注
                $('#green_channel_follow').empty()
                    .html(this.iconInSvg(icons.follow))
                    .append(`<span id="follow-count">${followCount}</span>`);
                //收藏
                $('#green_channel_favorite').empty()
                    .html(this.iconInSvg(icons.collect))
                //分享至微博
                $('#green_channel_weibo').empty()
                    .html(this.iconInSvg(icons.weibo))
                //分享至微信
                $('#green_channel_wechat').empty()
                    .html(this.iconInSvg(icons.wechat))
                resolve();
            });

        }

        // 设置图标
        setIcon() {
            const iconfont = urls.script.iconfont;
            this.loaderFile(iconfont, 'jsCDN');
            // 公告
            $('#sidebar_news .catListTitle').prepend(this.iconInSvg(icons.news));
            // 首页阅读全文
            $('.c_b_p_desc_readmore').append(this.iconInSvg(icons.readMore));
            if (this.isPostPage) {
                //随笔页题目
                $('.postTitle>a').prepend(this.emoji);
                //文章目录icon
                $('#catalog_title>h3').prepend(this.iconInSvg(icons.catalog));
                //文章签名icon
                $('#MySignature>p:first-child').prepend(this.iconInSvg(icons.signature));
                //文章评论列表icon
                $('.feedback_area_title').prepend(this.iconInSvg(icons.commentList));
                //文章评论icon
                $('.commentbox_title_left').prepend(this.iconInSvg(icons.writeComment));
                //侧边栏主标题icon
                $('#leftcontentcontainer .catListTitle')
                    .each(function () { $(this).text($(this).text().trim()); })
                    .prepend(this.iconInSvg(icons.catListTitle));

                let showPostTools = async () => {
                    try {
                        await this.setPostTools();
                        $('#blog_post_info').css({
                            'visibility': 'visible',
                            'animation': 'fadeIn 1s ease-in 0s'
                        });
                    } catch (err) {
                        console.error(err);
                    }
                }
                showPostTools();
            }
        }

        // 设置文章签名
        setPostSignature() {
            $('#MySignature').html(`
            <p>版权声明</p>
            <p>出处：博客园 ${userMessage.nickName}</p>
            <p>测试测试</p>
            <p>如果你能点击推荐，博主将感激不尽！</p>
        `);
        }

        // 设置文章目录
        setCatalog() {
            const $parentEle = $($('#cnblogs_post_body'));
            const $catalogContainer = $("<div>");
            const $ulContainer = $("<ul>");
            const titleReg = /^h[1-3]$/;
            let state = true;
            $catalogContainer.attr("id", "catalog").append($(`<div id='catalog_title'><h3>目录</h3><button class='control_btn'>-</button></div>`));
            // 查找文章中所有的h1、h2、h3标签
            // 生成目录列表插入目录容器中
            $parentEle.children().each(function () {
                if (titleReg.test(this.tagName.toLowerCase())) {
                    $(this).append("<a href='#catalog' class='title_back'> #</a>");

                    //生成目录列表
                    let aEle = $("<a></a>"),
                        hEle = $("<li></li>");
                    aEle.attr("href", "#" + this.id).text(this.childNodes[0].nodeValue);
                    hEle.attr("class", this.nodeName.toLowerCase() + "-list").append(aEle);

                    $ulContainer.append(hEle);
                }
            });
            // 替换[TOC]为目录
            $("#cnblogs_post_body > p").eq(0).replaceWith($catalogContainer.append($ulContainer));
            // 添加目录收缩功能
            $("#catalog button").on("click", function () {
                $("#catalog ul,#catalog_title h3").toggle();
                $(event.target).text(state ? "+" : "-");
                state = !state;
            });
        }

        // 设置网站图标
        setFavicon() {
            const config = 'www.dummyimage.com/50';
            if (config.favicon === '') return false;
            $('head').append(`<link rel="shortcut icon" href="${config.favicon}" type="image/x-icon" />`);
        }

        // 设置代码行号
        setLineNumbers() {
            const enable = this.defaultOptions.lineNumbers.enable;
            if (enable) this.loaderFile(urls.script.lineNumbers, 'js');
        }

        // 设置代码高亮主题
        setCodeTheme() {
            const highLight = this.defaultOptions.highLight.type;
            this.loaderFile(highLight, 'css');
        }

        // 代码块添加复制按钮
        setCopyBtn() {
            const pres = $('.postBody .cnblogs-markdown').find('pre');
            if (!pres.length) return false;
            $.each(pres, (index, pre) => { $(pre).prepend(`<div class="copy-btns">复制</div>`); });
            $('pre').on('click', '.copy-btns', function () {
                let sel = window.getSelection();
                sel.removeAllRanges();
                let range = document.createRange();
                range.selectNode($(this).siblings('code.hljs')[0]);
                sel.addRange(range);
                let txt = sel.anchorNode.innerText;
                let area = $('<textarea name="" id="board" cols="30" rows="10"></textarea>');
                area.val(txt);
                area[0].select();
                document.execCommand('copy');
                $(this).text('已复制');
            })
        }

        // 设置footer
        setFooter() {
            const config = this.defaultOptions.links;
            $('#footer').empty();
            let linkWrap = '<div id="links"><ul></ul></div>';
            let links = '';
            $('#footer').html(linkWrap);
            for (let i = 0; i < config.length; i++) {
                links += `<li><a href='${config[i].link}'>${config[i].name}</a></li>`;
            }
            $('#links ul').append(links);
            let cr = `<div id='copyright'>
                              <span>Copyright © 2019 ${userMessage.nickName}</span>
                              <span>Powered by <a href='https://code.visualstudio.com/'>VS Code 1.x</a> 🚀 Theme <a href='${urls.repositories.gitee}'>awesCnb ${this.v}</a> </span>
                          </div>`
            $('#footer').append(cr);
        }
    }
    new Light().init();
})($);
